<?php

namespace App\Http\Middleware;

use App\Http\Classes\User;
use Closure;

class VerifyUserToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ( isset($_COOKIE['TOKEN']) && $request->has('userid'))
        {
            $userId = $request->get('userid');
            $token = $_COOKIE['TOKEN'];
            $user = new User($userId);
            $user = $user->tokenVerify($token);
            if ( $user )
            {
                return $next($request);
            }
            else
            {
                return $this->response(0, '身份认证失败，请重新登录', null);
            }
        }
        else
        {
            return $this->response(0, 'TOKEN已过期，请重新登录', null);
        }
    }

    private function response($code, $msg, $data)
    {
        $res = [];
        $res['code'] = $code;
        $res['msg'] = $msg;
        $res['data'] = $data;
        return response()->json($res);
    }
}
